package com.jltx.storage.downloader;


import org.apache.http.conn.ConnectTimeoutException;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLException;

/**
 * @author jltxseo
 * Created by junlintianxia on 2019/12/02.
 */
public class RequestException extends Exception {

    public static final int CODE_ERROR_SOCKET_EXCEPTION = -10000;
    public static final int CODE_ERROR_CONNECT_TIME_OUT = -10001;
    public static final int CODE_ERROR_SOCKET_TIMEOUT = -10002;
    public static final int CODE_ERROR_SSL_EXCEPTION = -10003;
    public static final int CODE_ERROR_IO_EXCEPTION = -10004;
    public static final int CODE_ERROR_NO_NETWORK = -10005;
    public static final int CODE_ERROR_CANCELED = -10006;
    public static final int CODE_ERROR_UNKNOWN_HOST = -10007;
    public static final int CODE_ERROR_OTHER_EXCEPTION = -10008;


    public final int code;
    public final String message;
    public final Throwable cause;

    public RequestException(int code, String message, Throwable cause) {
        this.code = code;
        this.message = message;
        this.cause = cause;
    }

    public RequestException(int code, String message) {
        this.code = code;
        this.message = message;
        this.cause = null;
    }


    public static RequestException transformException(Throwable error) {
        if (!NetWorkUtil.isAvailable(Downloader.getInstance().getContext())) {
            return new RequestException(RequestException.CODE_ERROR_NO_NETWORK, "No Network");
        } else if (error instanceof RequestException) {
            return (RequestException) error;
        } else if (error instanceof ConnectTimeoutException) {
            return new RequestException(CODE_ERROR_CONNECT_TIME_OUT, "Connect TimeOut!Msg:" + error.getMessage(), error);
        } else if (error instanceof SocketTimeoutException) {
            return new RequestException(CODE_ERROR_SOCKET_TIMEOUT, "Socket TimeOut!Msg:" + error.getMessage(), error);
        } else if (error instanceof SocketException) {
            return new RequestException(CODE_ERROR_SOCKET_EXCEPTION, "Socket Exception! Msg:" + error.getMessage(), error);
        } else if (error instanceof SSLException) {
            return new RequestException(CODE_ERROR_SSL_EXCEPTION, "SSL Exception! Msg:" + error.getMessage(), error);
        } else if (error instanceof UnknownHostException) {
            return new RequestException(CODE_ERROR_UNKNOWN_HOST, "Unknown Host! Msg: " + error.getMessage(), error);
        } else if (error instanceof IOException) {
            return new RequestException(CODE_ERROR_IO_EXCEPTION, "IOException! Msg:" + error.getMessage(), error);
        } else {
            return new RequestException(CODE_ERROR_IO_EXCEPTION, "Other Exception! Msg:" + (error != null ? error.getMessage() : ""), error);
        }

    }
}
